<?php
class Media extends CI_Controller
{
	public function __construct ()
	{
		parent::__construct();
		$this->template->set_template('template/admin_template');
		if($this->general_model->loggedin("admin") == FALSE)
		{
			redirect('admin/users/login');
		}
	}
	public function index()
	{
		$data['breadcrumb'] = set_crumbs(array(current_url() => 'Media'));
        $data['allmedia'] = $this->get_upload_files('{jpg,png,pdf}', 'assets/uploads/images');
		/*echo "<pre>";
		print_r($data['allmedia']);*/
		
		$this->template->content->view('admin/media/media', $data);
		$this->template->publish();
	}
	function get_upload_files($extension = '', $directory = '/')
    {
        //$theme_dir = base_url();
		$theme_dir = CMS_ROOT ;
        $pattern = $theme_dir . trim($directory, '/') . '/*.' . $extension;
		//echo $pattern;
        $file_array = array();
        $files = glob_recursive($pattern, GLOB_BRACE);
		
		foreach ($files as $file)
        {
            $relative_path = str_replace(dirname($pattern) . '/', '', $file);
			
            $theme_path = str_replace($theme_dir, '', $file);

            $file_array[$relative_path] = array(
                'theme_path'    => $theme_path,
                'relative_path' => $relative_path,
                'title'         => ucwords(str_replace(array('_', '-'), ' ', basename($file, '.' . $extension))),
				'file_extension' =>pathinfo($file, PATHINFO_EXTENSION)
			);
        }
        return $file_array;
    }
	public function addmedia()
	{
		$data['breadcrumb'] = set_crumbs(array('media' => 'Media', current_url() => 'Add Media'));
		
		
		$this->template->add_package(array('dropzone'));
		$this->template->content->view('admin/media/addmedia', $data);
		$this->template->publish();
	}
	public function mediaupload()
	{
		if(!empty($_FILES))
		{
			$this->load->library('upload');
			/*main image upload*/
			$configmain = array(
							'allowed_types' => '*', 
							'upload_path' => FCPATH . 'assets/uploads/images/media', 
							'max_size' => 2097152,
							'overwrite' => TRUE, 
							);
			$this->upload->initialize($configmain); 
			if ($this->upload->do_upload('file'))
			{
				$data = array('upload_data' => $this->upload->data());
									
				//to create thumbnail
				$config = array(
							'source_image' => $data['upload_data']['full_path'], //get original image
							'new_image' => FCPATH . 'assets/uploads/.thumbs/images/media/', //save as new image //need to create thumbs first
							'maintain_ratio' => true, 
							'width' => 220,
							'height' =>235   
						);
			 
				$this->load->library('image_lib'); 
				$this->image_lib->clear();
				$this->image_lib->initialize($config);
				$this->image_lib->resize();//load library
				 
			}
		}
	}
	public function editgallery()
	{
		$data['breadcrumb'] = set_crumbs(array('gallery' => 'Gallery', current_url() => 'Edit Gallery'));
		$galleryid=$this->uri->segment(4);
		$this->form_validation->set_rules('title', 'Gallery Name', 'trim|required|max_length[255]');

        // Form validation
        if ($this->form_validation->run() == TRUE)
        {
            $gallerydetails=array(
					'title'=>$this->input->post('title'),
					"short_name"=>$this->input->post('short_name')
					);
			$this->general_model->update('galleries',$gallerydetails,'id = '.$galleryid);
            $this->session->set_flashdata('message', '<p class="success">Gallery Renamed Saved.<p>');

            redirect(ADMIN_PATH . '/gallery');
        }
		$data['gallery']=$this->general_model->select_val("galleries","*","id = ".$galleryid);
		$this->template->content->view('admin/gallery/editgallery', $data);
		$this->template->publish();
	}public function deletegallery()
	{
		if ($this->input->post('selected'))
        {
            $selected = $this->input->post('selected');
        }
        else
        {
            $selected = (array) $this->uri->segment(5);
        }
		$this->general_model->delete_rows('galleries','id',$selected);
		$this->session->set_flashdata('message', '<p class="success">Gallery deleted Successfully.</p>');
		redirect(ADMIN_PATH . "/gallery");
	}
	public function images()
	{
        $data['galleryid']=$galleryid = $this->uri->segment(4);
        $data['breadcrumb'] = set_crumbs(array('gallery' => 'Gallery', current_url() => 'Images'));
        $this->template->javascript->add('/assets/admin/js/jquery.tablednd_0_5.js'); 
       
        // Get data from db
		$data['Images'] = $this->general_model->select_ord("gallery_images","*","sort","ASC","gallery_id = ".$galleryid);

        $_SESSION['KCFINDER'] = array();
        $_SESSION['KCFINDER']['disabled'] = false;
        $_SESSION['isLoggedIn'] = true;
		$this->template->content->view('admin/gallery/images', $data);
		$this->template->publish();
       
	}
	public function addimages()
	{
		if (is_ajax() && $this->input->post('files') && $this->input->post('gallery_id'))
        {
            
           $sort=$this->general_model->selectmax("gallery_images","sort","","gallery_id = ".$this->input->post('gallery_id'));
		   $sort=$sort['sort'];
		 
            // Insert selected images
            foreach($this->input->post('files') as $filename)
            {
                $filename = urldecode($filename);
				$lastSlashpos = strpos($filename, "images/");

				$fileName = substr($filename,$lastSlashpos+7);
                $gallery_id = $this->input->post('gallery_id');

                $info = pathinfo(urldecode($filename));
				
                $title = ucwords(str_replace(array('_', '-'), ' ', $info['filename']));

                $sort++;
				$gallerydata=array("filename"=>$fileName,
									"title"=>$title,
									"gallery_id"=>$gallery_id,
									"sort"=>$sort);
                $this->general_model->insert("gallery_images",$gallerydata);
				
            }
        }
        else
        {
            return show_404();
        }
	}
	public function editimage()
	{
		$data['galleryid']=$galleryid=$this->uri->segment(4);
		$data['breadcrumb'] = set_crumbs(array('gallery' => 'Gallery','gallery/images/'.$galleryid => 'Images', current_url() => 'Edit Images'));
		
		$imageid=$this->uri->segment(5);
		$data['Image']=$this->general_model->select_val("gallery_images","*","id = ".$imageid);
		
		$this->form_validation->set_rules('title', 'Title', "trim|required");
        $this->form_validation->set_rules('alt', 'Alternative Text', "trim");
        $this->form_validation->set_rules('description', 'Description', 'trim');
        $this->form_validation->set_rules('filename', 'filename', 'trim|required');
        $this->form_validation->set_rules('hide', 'Hide', 'trim|integer');

        // Form validation
        if ($this->form_validation->run() == TRUE)
        {
            $imagedata=array("filename"=>$this->input->post('filename'),
							"title"=>$this->input->post('title'),
							"alt"=>$this->input->post('alt'),
							"description"=>$this->input->post('description'),
							"hide"=>($this->input->post('hide')) ? 1 : 0);
			$this->general_model->update('gallery_images',$imagedata,'id = '.$imageid);
            $this->session->set_flashdata('message', '<p class="success">Image Updated Saved.<p>');

            redirect(ADMIN_PATH . '/gallery/images/'.$galleryid);
        }
		$_SESSION['KCFINDER'] = array();
        $_SESSION['KCFINDER']['disabled'] = false;
        $_SESSION['isLoggedIn'] = true;
		$this->template->content->view('admin/gallery/editimage', $data);
		$this->template->publish();
	}
	public function images_order()
	{
		// Order images
        if (is_ajax())
        {
            if(count($_POST) > 0 && $this->input->post('image_table'))
            {
                
                $table_order = $this->input->post('image_table');

                unset($table_order[0]);
                $table_order = array_values($table_order);
				print_r($table_order);
                $i = 1;
                foreach($table_order as $id)
                {
					$updatesort=array("sort"=>$i);
					$this->general_model->update("gallery_images",$updatesort,"id = ".$id);
                    $i++;
                }
            }

            return;
        }
        else
        {
            return show_404();
        }
	}
	public function deleteimage($galleryid)
	{
		if ($this->input->post('selected'))
        {
            $selected = $this->input->post('selected');
        }
        else
        {
            $selected = (array) $this->uri->segment(5);
        }
		$this->general_model->delete_rows('gallery_images','id',$selected);
		$this->session->set_flashdata('message', '<p class="success">Images deleted Successfully.</p>');
		redirect(ADMIN_PATH . "/gallery/images/".$galleryid);
	}
	
}
?>